package com.zhonglian.elisa.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by wyb on 2018/5/9.
 * 修改 - Yx
 */

public class StatusBarUtil {
    public static int statusBarHeight = -1;
    public static int navigationHeight = -1;


    /**
     * Created : Yx
     * 通过Resource类，获取资源文件ID,获取到状态栏高度
     */
    public static int getStatusBarHeight2(Context context) {
        if (statusBarHeight != -1) {
            return statusBarHeight;
        }
        int result = 0;
        int resourceId = context.getResources().getIdentifier(
                "status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        statusBarHeight = result;
        return statusBarHeight;
    }

    /**
     * 获取底部导航栏高度
     *
     * @return
     */
    public static int getNavigationBarHeight(Context context) {
        if (navigationHeight != -1) {
            return navigationHeight;
        }
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        //获取NavigationBar的高度
        navigationHeight = resources.getDimensionPixelSize(resourceId);
        return navigationHeight;
    }

    /**
     * 获取是否存在虚拟导航栏NavigationBar
     * true 有  false 无
     */
    public boolean checkDeviceHasNavigationBar(Context mContext) {
        boolean hasNavigationBar = false;
        Resources rs = mContext.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
        }
        return hasNavigationBar;
    }


    /**
     * 设置布局在虚拟导航上面
     *
     * @param window
     */
    public static void setToNavigationBarTOP(Window window) {//Flag属性5.0才可用
        int uiOptions =
                //让应用占用状态栏空间设两SYSTEM_UI_FLAG_LAYOUT_STABLE | Flag:SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                        //让布局内容占用导航栏空间设下1 Flag:SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                        //让界面全屏设1 Flag:SYSTEM_UI_FLAG_FULLSCREEN
                        //View.SYSTEM_UI_FLAG_FULLSCREEN |
                        //状态栏文字颜色 SYSTEM_UI_FLAG_LIGHT_STATUS_BAR黑色 | SYSTEM_UI_FLAG_LAYOUT_STABLE系统默认色白或其他
                        View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR |
                        //隐藏导航栏设下面两个Flag: |SYSTEM_UI_FLAG_HIDE_NAVIGATION 首次点屏幕会显示 | View.SYSTEM_UI_FLAG_IMMERSIVE不在显示|
                        // View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY,这个属性的意思是，底部向上滑动显示导航栏后，导航栏在几秒后自动隐藏，
                        // 不过再次弹出导航栏， 不会触发OnSystemUiVisibilityChangeListener事件，而且导航栏会遮挡屏幕
                        // |SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN 布局充满，状态栏与导航栏共用该属性
                        View.SYSTEM_UI_FLAG_IMMERSIVE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
        if (Build.VERSION.SDK_INT >= 19) {
            //uiOptions |= 0x00001000;//状态栏 指 对半透明的显示方法。又称“点透”。图形处理较差的设备往往用“点透”替代Alpha混合。
        } else {
            uiOptions |= View.SYSTEM_UI_FLAG_LOW_PROFILE;//状态栏显示处于低能显示状态(low profile模式)，状态栏上一些图标显示会被隐藏。 图标变小，变模糊或者弱化其效果
        }
        window.getDecorView().setSystemUiVisibility(uiOptions);//setSystemUiVisibility和getSystemUiVisibility方法实现对状态栏导航栏的动态显示或隐藏的操作，以及获取状态栏当前可见性
        //系统栏的可见性更改时接收回调
        window.getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
            }
        });
    }


    //=========================修改↓状态栏颜色,文字颜色===============================

    /**
     * @param activity
     * @param colorRes 状态栏的颜色，传 0 为透明色
     */
    public static void setStatusBarColor(Activity activity, int colorRes) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = activity.getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            if (colorRes > 0) {
                activity.getWindow().setStatusBarColor(activity.getResources().getColor(colorRes));
            } else {
                activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = activity.getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
    }

    /**
     * 设置状态栏文字色值为深色调
     * true为灰色，false为系统默认白
     *
     * @param useDart  是否使用深色调
     * @param activity
     */
    public static void setStatusTextColor(boolean useDart, Activity activity) {
        if (isFlyme()) {
            processFlyMe(useDart, activity);
        } else if (isMIUI() && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            processMIUI(useDart, activity);
        } else {
            if (useDart) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                }
            } else {
                activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            }
            //activity.getWindow().getDecorView().findViewById(android.R.id.content).setPadding(0, statusBarHeight, 0, 0);
        }
    }

    /**
     * 改变魅族的状态栏字体为黑色，要求FlyMe4以上
     */
    private static void processFlyMe(boolean isLightStatusBar, Activity activity) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        try {
            Class<?> instance = Class.forName("android.view.WindowManager$LayoutParams");
            int value = instance.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON").getInt(lp);
            Field field = instance.getDeclaredField("meizuFlags");
            field.setAccessible(true);
            int origin = field.getInt(lp);
            if (isLightStatusBar) {
                field.set(lp, origin | value);
            } else {
                field.set(lp, (~value) & origin);
            }
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
    }

    /**
     * 改变小米的状态栏字体颜色为黑色, 要求MIUI6以上  lightStatusBar为真时表示黑色字体
     */
    private static void processMIUI(boolean lightStatusBar, Activity activity) {
        Class<? extends Window> clazz = activity.getWindow().getClass();
        try {
            int darkModeFlag;
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), lightStatusBar ? darkModeFlag : 0, darkModeFlag);
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
    }

    private static final String KEY_MIUI_VERSION_CODE = "ro.miview.view.version.code";
    private static final String KEY_MIUI_VERSION_NAME = "ro.miview.view.version.name";
    private static final String KEY_MIUI_INTERNAL_STORAGE = "ro.miview.internal.storage";

    /**
     * 判断手机是否是小米
     *
     * @return
     */
    public static boolean isMIUI() {
        try {
            final BuildProperties prop = BuildProperties.newInstance();
            return prop.getProperty(KEY_MIUI_VERSION_CODE, null) != null
                    || prop.getProperty(KEY_MIUI_VERSION_NAME, null) != null
                    || prop.getProperty(KEY_MIUI_INTERNAL_STORAGE, null) != null;
        } catch (final IOException e) {
            return false;
        }
    }

    /**
     * 判断手机是否是魅族
     *
     * @return
     */
    public static boolean isFlyme() {
        try {
            // Invoke Build.hasSmartBar()
            final Method method = Build.class.getMethod("hasSmartBar");
            return method != null;
        } catch (final Exception e) {
            return false;
        }
    }


}